package com.cssl.utils;

import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: chen
 * @Date: 2021/11/14 23:14
 * @Desc:
 */
public class JdbcUtil {

    /**
     * 通用查询
     *
     * @param connection        数据库连接
     * @param querySql          查询的sql
     * @param clz               泛型
     * @param underScoreToCamel 下划线转驼峰
     * @return {@link List}     返回结果集
     */
    public static <T> List<T> queryList(Connection connection, String querySql, Class<T> clz, Boolean underScoreToCamel) throws SQLException, IllegalAccessException, InstantiationException, InvocationTargetException {
        //创建集合用于存放查询结果数据
        ArrayList<T> resultList = new ArrayList<>();

        //预编译sql
        PreparedStatement preparedStatement = connection.prepareStatement(querySql);

        //执行查询
        ResultSet resultSet = preparedStatement.executeQuery();

        //解析resultSet
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        while (resultSet.next()) {
            //创建泛型对象
            T t = clz.newInstance();

            //给泛型对象赋值
            for (int i = 1; i < columnCount + 1; i++) {
                //获取列名
                String columnName = metaData.getColumnName(i);

                //判断是否需要转换为驼峰命名
                if (underScoreToCamel) {
                    columnName = CaseFormat.LOWER_UNDERSCORE.to(
                            CaseFormat.LOWER_CAMEL,
                            columnName.toLowerCase());
                }
                //获取列值
                Object value = resultSet.getObject(i);

                //给泛型对象赋值
                BeanUtils.setProperty(t, columnName, value);
            }
            //将该对象添加至集合
            resultList.add(t);
        }

        //关闭资源
        preparedStatement.close();
        resultSet.close();

        //返回结果集
        return resultList;
    }
}
